public class Main {
    static int m, n;
    static char[] word;
    static boolean[][] used;
    static int[] dx = {0,0,1,-1};
    static int[] dy = {1,-1,0,0};

    public static boolean exist(char[][] board, String _word) {
        m = board.length;
        n = board[0].length;
        word = _word.toCharArray();
        used = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == word[0]) {
                    used[i][j] = true;
                    if(dfs(board,i,j,1)) return true;
                    used[i][j] = false;
                }
            }
        }
        return false;
    }

    public static boolean dfs(char[][] board, int i, int j,int pos) {
        if(pos == word.length) return true;
        for(int k = 0;k < 4;k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && !used[x][y] && board[x][y] == word[pos]) {
                used[x][y] = true;
                if(dfs(board,i+x,j+y,pos+1)) return true;
                used[x][y] = false;
            }
        }
        return false;
    }

    public static void main(String[] args) {

    }
}
